/*
 *  BlobTracker.h
 *  portVideoBlobDetection
 *
 *  Created by Pawe? So?yga on 7/27/07.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */
 #include "ITouchListener.h"
 #include "BlobDetection.h"
#include "Blob.h"
//#include <ext/hash_map>
#include <vector>
#include <map>
#include <algorithm>
#include <string>

//using namespace __gnu_cxx; 

class BlobExt
{
public:
	TouchData td;
	std::vector< std::pair<int, float> > closest;
};


struct ClosestDistanceSort
{
     bool operator()(const BlobExt& start, const BlobExt& end)
     {
          return start.closest[0].second < end.closest[0].second;
     }
};

// Ascending distance sorting function
struct AscendingDistanceSort
{
     bool operator()(const std::pair<int, float>& start, const std::pair<int, float>& end)
     {
          return start.second < end.second;
     }
};

class BlobTracker
{
private:
	std::map<int, bool> currentBlobsIds;
	std::map<int, bool> previousBlobsIds;
	std::vector<BlobExt> currentBlobs;
	std::vector<BlobExt> previousBlobs;
	blobDetection::BlobDetection *bd;
	blobDetection::Blob b;
	
	std::map<std::string, ITouchListener *> listenersMap;
	float threshold;
	int lastId;
	
	float getDistance(TouchData b1, TouchData b2);
	int getNextFreeId();
	void sortBlobsClosestByDistance();
	void sortBlobsByClosest();
	void calculateAllDistances();
	
public:
	BlobTracker();
	void convertBlobsToTouchData();
	void setBlobAlgorithm(blobDetection::BlobDetection *bd);
	void setThreshold(float threshold);
	void track();
	void processPureData();

	void doUpEvent(TouchData td);
	void doDownEvent(TouchData td);
	void doUpdateEvent(TouchData td);
	bool addListener(ITouchListener *listener, std::string listenerName);
	bool removeListener(ITouchListener *listener);
	bool removeListener(std::string listenerName);
};